## setup ##

# clean environment
rm(list=ls())

# load data
dat_outcomes <- read.csv2("data_experiment_outcomes_csv.csv",
                          encoding = 'UTF-8')


dat_covars <- read.csv2("data_experiment_covariates_csv.csv",
                       encoding = 'UTF-8')

# outcomes to numeric
dat_outcomes$response <- as.numeric(as.character(dat_outcomes$response))
dat_outcomes$quality_notimputed <- as.numeric(as.character(dat_outcomes$quality_notimputed))
dat_outcomes$response_id <- as.numeric(as.character(dat_outcomes$response_id))
dat_outcomes$day_diff_notimputed <- as.numeric(as.character(dat_outcomes$day_diff_notimputed))

# age to numeric
dat_covars$age_notimputed <- as.numeric(as.character(dat_covars$age_notimputed))


## table with descriptives ##

# define variables
vars_outcomes <- c("response", "quality_notimputed", "response_id", "day_diff_notimputed")
vars_covars <- c("migrant", "female", "age_notimputed", "east", "day", "cdu_csu", "spd", "gruene", "fdp", "linke", "afd")

# function to get summary statistics
desc_outcomes <- lapply(vars_outcomes, function(x) {
  cbind(sum(!is.na(dat_outcomes[,x])), round(mean(dat_outcomes[,x], na.rm=T),2), round(sd(dat_outcomes[,x], na.rm=T), 2), min(dat_outcomes[,x], na.rm=T), max(dat_outcomes[,x], na.rm=T))
})
desc_covars <- lapply(vars_covars, function(x) {
  cbind(sum(!is.na(dat_covars[,x])), round(mean(dat_covars[,x], na.rm=T),2), round(sd(dat_covars[,x], na.rm=T), 2), min(dat_covars[,x], na.rm=T), max(dat_covars[,x], na.rm=T))
})

# create table
desc_df <- rbind.data.frame(do.call(rbind.data.frame, desc_outcomes),do.call(rbind.data.frame, desc_covars))
row.names(desc_df) <- c(vars_outcomes, vars_covars)
names(desc_df) <- c("N", "Mean", "SD", "Min.", "Max.")
row.names(desc_df) <- c("Response", "Response Content", "Personal Response from MP", "Time Until Response (Days)",
                        "MP Immigrant Background", "MP Female", "MP Age", "East Germany", "Day of Email Dispatch",
                        "CDU/CSU", "SPD", "Greens", "FDP", "Left Party", "AfD")

# show table
desc_df
